package org.lex.ftp.ui.speed;

import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.table.AbstractTableModel;

import org.lex.net.ftp.FTPURL;


public class SpeedTableModel extends AbstractTableModel {
	private final String[] columnNames = { "Server", "Status", "Speed", "Path" };
	public ArrayList<FTPURL> ftpUrls = null;
	public ArrayList<ServerStatus> status = null;
	private ArrayList<Long> speeds = null;

	public SpeedTableModel() {
		super();
		this.ftpUrls = new ArrayList<FTPURL>();
		this.status = new ArrayList<ServerStatus>();
		this.speeds = new ArrayList<Long>();
	}

	public FTPURL getRow(int row) {
		return this.ftpUrls.get(row);
	}

	public String getColumnName(int column) {
		return this.columnNames[column];
	}

	public int getRowCount() {
		return ftpUrls.size();
	}

	public int getColumnCount() {
		return columnNames.length;
	}

	public Object getValueAt(int row, int column) {
		FTPURL ftpUrl = ftpUrls.get(row);
		switch (column) {
		case 0:
			return ftpUrl.toString();
		case 1:
			return status.get(row);
		case 2:
			return speeds.get(row);
		case 3:
			return ftpUrl.getPath();
		default:
			return null;
		}
	}

	void setStatus(int index, ServerStatus status) {
		this.status.set(index, status);
	}

	public void setSpeed(int index, long speed) {
		this.speeds.set(index, speed);
	}

	public void addServer(FTPURL ftpUrl, ServerStatus status, long speed) {
		this.ftpUrls.add(ftpUrl);
		if (null == status)
			this.status.add(ServerStatus.Unkown);
		else
			this.status.add(status);
		this.speeds.add(speed);
	}

	public void clearConnectFailed() {
		this.clearItem(new ServerStatus[] { ServerStatus.ConnectFailed });
	}

	public void clearNoSuchFile() {
		this.clearItem(new ServerStatus[] { ServerStatus.NoSuchFile });
	}

	public void clearBoth() {
		this.clearItem(new ServerStatus[] { ServerStatus.ConnectFailed, ServerStatus.NoSuchFile });
	}

	public void clearAll() {
		this.ftpUrls.clear();
		this.status.clear();
		this.speeds.clear();
		this.fireTableDataChanged();
	}

	private void clearItem(ServerStatus[] condition) {
		Arrays.sort(condition);
		for (int i = ftpUrls.size() - 1; i >= 0; i--) {
			if (Arrays.binarySearch(condition, status.get(i)) >= 0) {
				ftpUrls.remove(i);
				status.remove(i);
				speeds.remove(i);
			}
		}
		this.fireTableDataChanged();
	}
}
